<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8" />
        <title>01_复习</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }

            div {
                position: absolute;
                width: 100px;
                height: 100px;
                background-color: aqua;
            }
        </style>
    </head>
    <body>
        <div>尚硅谷</div>

        <script>
            var div = document.querySelector('div');

            div.onmousedown = function(event){
                var eleX = div.offsetLeft;
                var eleY = div.offsetTop;

                var startX = event.clientX;
                var startY = event.clientY;

                document.onmousemove = function(event){
                    var endX = event.clientX;
                    var endY = event.clientY;

                    var disX = endX - startX;
                    var disY = endY - startY;

                    var lastX = eleX + disX;
                    var lastY = eleY + disY;


                    if(lastX >= document.documentElement.clientWidth - div.offsetWidth){
                        lastX = document.documentElement.clientWidth - div.offsetWidth
                    }else if(lastX <= 0){
                        lastX = 0;
                    }

                    if(lastY >= document.documentElement.clientHeight - div.offsetHeight){
                        lastY = document.documentElement.clientHeight - div.offsetHeight
                    }else if(lastY <= 0){
                        lastY = 0;
                    }

                    if(lastX >= document.documentElement.clientWidth - div.offsetWidth - 50){
                        lastX = document.documentElement.clientWidth - div.offsetWidth
                    }else if(lastX <= 50){
                        lastX = 0;
                    }

                    if(lastY >= document.documentElement.clientHeight - div.offsetHeight - 50){
                        lastY = document.documentElement.clientHeight - div.offsetHeight
                    }else if(lastY <= 50){
                        lastY = 0;
                    }

                    div.style.left = lastX + 'px';
                    div.style.top = lastY + 'px';
                }

                document.onmouseup = function(){
                    document.onmousemove = document.onmouseup = null;
                }

                return false;
            }
        </script>
    </body>
</html>